import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:plate_lpr/plate_lpr.dart';

void main() {
  print("进入应用了");
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '车牌识别插件示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: '车牌识别插件示例'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _lastResult = '暂无结果';
  bool _isRecognizing = false;
  String? _lastImagePath;
  String? _watermarkedImagePath; // 用于显示可能已添加水印的图片
  PlateLprResult? _lastRecognitionResult; // 使用类型安全的结果对象
  Map<String, dynamic>? _imageInfo;

  /// 获取图片信息（像素尺寸和文件大小）
  Future<Map<String, dynamic>?> _getImageInfo(String imagePath) async {
    try {
      final file = File(imagePath);
      if (!file.existsSync()) {
        return null;
      }
      final fileSize = await file.length();
      final Uint8List imageBytes = await file.readAsBytes();
      final image = await decodeImageFromList(imageBytes);
      return {
        'width': image.width,
        'height': image.height,
        'fileSize': fileSize,
        'fileSizeFormatted': _formatFileSize(fileSize),
      };
    } catch (e) {
      print('获取图片信息失败: $e');
      return null;
    }
  }

  /// 格式化文件大小
  String _formatFileSize(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    } else {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    }
  }

  /// 启动识别
  Future<void> _startRecognition(RecogButtonType recogButtonType) async {
    setState(() {
      _isRecognizing = true;
      _lastResult = '正在启动识别...';
      _lastImagePath = null;
      _watermarkedImagePath = null;
      _imageInfo = null;
      _lastRecognitionResult = null;
    });

    try {
      final result = await PlateLpr.startRecognition(
        config: PlateLprConfig(
          recogButtonType: recogButtonType,
          title: '请对准车牌',
        ),
      );

      // 获取图片信息
      Map<String, dynamic>? imageInfo;
      if (result.imagePath != null && result.imagePath!.isNotEmpty) {
        imageInfo = await _getImageInfo(result.imagePath!);
      }

      setState(() {
        _lastRecognitionResult = result;
        _lastImagePath = result.imagePath;
        _watermarkedImagePath = _lastImagePath; // 初始路径
        _imageInfo = imageInfo;
        _lastResult = _formatResult(result);
      });

      _showResultDialog();
    } catch (e) {
      setState(() {
        _lastResult = '识别失败: $e';
      });
      _showDialog('错误', '启动识别失败: $e');
    } finally {
      setState(() {
        _isRecognizing = false;
      });
    }
  }

  /// 格式化结果用于显示
  String _formatResult(PlateLprResult result) {
    if (!result.success) {
      if (result.plateNumber == 'back') return '操作结果: 用户返回';
      return result.error ?? '识别失败: 未知错误';
    }

    final plateNumber = result.plateNumber ?? '';
    final confidence = result.confidence ?? 0.0;

    switch (plateNumber) {
      case 'noplate':
        return '操作结果: 无牌车';
      case 'input':
        return '操作结果: 手动输入';
      case 'error':
        return '识别失败: 未识别到车牌';
      default:
        if (plateNumber.isNotEmpty) {
          return '识别结果: $plateNumber\n置信度: ${confidence.toStringAsFixed(2)}';
        } else {
          return '识别失败: 未识别到车牌';
        }
    }
  }

  void _showResultDialog() {
    if (_lastRecognitionResult == null) return;

    final result = _lastRecognitionResult!;
    final imagePath = result.imagePath;

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('识别完成'),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _formatResult(result),
                  style: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.bold),
                ),
                if (imagePath != null && imagePath.isNotEmpty) ...[
                  const SizedBox(height: 16),
                  const Text('识别图片:',
                      style:
                          TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
                  const SizedBox(height: 8),
                  Container(
                    width: double.infinity,
                    height: 200,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: File(imagePath).existsSync()
                          ? InteractiveViewer(
                              panEnabled: true, // 允许平移
                              minScale: 0.5,
                              maxScale: 4.0,
                              child: Image.file(
                                File(imagePath),
                                fit: BoxFit.contain,
                                errorBuilder: (context, error, stackTrace) {
                                  return const Center(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Icon(Icons.error, color: Colors.red),
                                        Text('图片加载失败',
                                            style:
                                                TextStyle(color: Colors.red)),
                                      ],
                                    ),
                                  );
                                },
                              ),
                            )
                          : const Center(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(Icons.image_not_supported,
                                      color: Colors.grey),
                                  Text('图片不存在',
                                      style: TextStyle(color: Colors.grey)),
                                ],
                              ),
                            ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text("图片路径: $imagePath",
                      style: const TextStyle(fontSize: 12, color: Colors.grey)),
                  if (_imageInfo != null) ...[
                    const SizedBox(height: 8),
                    const Text("图片信息:",
                        style: TextStyle(
                            fontSize: 12, fontWeight: FontWeight.bold)),
                    Text(
                        "像素尺寸: ${_imageInfo!['width']}×${_imageInfo!['height']}",
                        style:
                            const TextStyle(fontSize: 12, color: Colors.grey)),
                    Text("文件大小: ${_imageInfo!['fileSizeFormatted']}",
                        style:
                            const TextStyle(fontSize: 12, color: Colors.grey)),
                  ],
                ],
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  void _showDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title),
          content: Text(content),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  /// 为最后一张识别的图片添加水印
  Future<void> _addWatermark() async {
    if (_lastImagePath == null || _lastImagePath!.isEmpty) {
      _showDialog('提示', '请先进行一次车牌识别以获取图片。');
      return;
    }

    // 检查原图片是否存在
    if (!File(_lastImagePath!).existsSync()) {
      _showDialog('错误', '原图片文件不存在，无法添加水印。');
      return;
    }

    setState(() {
      _isRecognizing = true;
      _lastResult = '正在添加水印...';
    });

    try {
      final watermarkText =
          '车牌: ${_lastRecognitionResult?.plateNumber ?? 'N/A'}\n'
          '时间: ${DateTime.now().toString().substring(0, 19)}';

      print('开始添加水印到图片: $_lastImagePath');
      print('水印文本: $watermarkText');

      final newPath = await PlateLpr.addWatermark(
        imagePath: _lastImagePath!,
        text: watermarkText,
        textColor: Colors.white,
        textSize: 36.0,
        backgroundColor: Colors.black.withOpacity(0.5),
      );

      print('水印添加结果路径: $newPath');

      if (newPath != null && newPath.isNotEmpty) {
        // 验证新文件是否存在
        if (File(newPath).existsSync()) {
          // 强制清除所有相关的图片缓存
          if (_watermarkedImagePath != null) {
            final oldImageProvider = FileImage(File(_watermarkedImagePath!));
            await oldImageProvider.evict();
          }

          final newImageProvider = FileImage(File(newPath));
          await newImageProvider.evict();

          // 等待一小段时间确保文件系统操作完成
          await Future.delayed(const Duration(milliseconds: 100));

          // 重新获取图片信息
          final newImageInfo = await _getImageInfo(newPath);

          setState(() {
            _watermarkedImagePath = newPath;
            _imageInfo = newImageInfo;
            _lastResult = '水印添加成功\n图片路径: $newPath';
          });

          print('水印添加成功，图片已更新');
          _showDialog('成功', '水印已成功添加！\n新图片路径: $newPath');
        } else {
          throw Exception('水印添加后的文件不存在: $newPath');
        }
      } else {
        throw Exception('水印添加失败，返回路径为空');
      }
    } catch (e) {
      print('添加水印失败: $e');
      setState(() {
        _lastResult = '水印添加失败: $e';
      });
      _showDialog('错误', '添加水印失败: $e');
    } finally {
      setState(() {
        _isRecognizing = false;
      });
    }
  }

  Widget _buildRecognitionButton({
    required String label,
    required RecogButtonType type,
    required IconData icon,
  }) {
    return ElevatedButton.icon(
      onPressed: _isRecognizing ? null : () => _startRecognition(type),
      icon: _isRecognizing
          ? Container(
              width: 20,
              height: 20,
              child: const CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            )
          : Icon(icon),
      label: Text(label),
      style: ElevatedButton.styleFrom(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        textStyle: const TextStyle(fontSize: 16),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              _buildRecognitionButton(
                label: '启动识别 (无牌车模式)',
                type: RecogButtonType.noPlate,
                icon: Icons.no_photography,
              ),
              const SizedBox(height: 20),
              _buildRecognitionButton(
                label: '启动识别 (手动输入模式)',
                type: RecogButtonType.manualInput,
                icon: Icons.edit,
              ),
              const SizedBox(height: 10),
              ElevatedButton.icon(
                onPressed: (_isRecognizing || _lastImagePath == null)
                    ? null
                    : _addWatermark,
                icon: const Icon(Icons.brush),
                label: const Text('添加水印'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.teal,
                  padding:
                      const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                  textStyle: const TextStyle(fontSize: 16),
                ),
              ),
              const SizedBox(height: 20),
              Expanded(
                child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.grey[300]!),
                  ),
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '最近识别结果:',
                          style: TextStyle(
                              fontSize: 14, fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          _lastResult,
                          style: const TextStyle(fontSize: 14),
                          textAlign: TextAlign.left,
                        ),
                        if (_watermarkedImagePath != null &&
                            _watermarkedImagePath!.isNotEmpty) ...[
                          const SizedBox(height: 12),
                          const Text(
                            '识别图片:',
                            style: TextStyle(
                                fontSize: 14, fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(height: 8),
                          Container(
                            width: double.infinity,
                            height: 150,
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: File(_watermarkedImagePath!).existsSync()
                                  ? InteractiveViewer(
                                      panEnabled: true,
                                      minScale: 0.5,
                                      maxScale: 4.0,
                                      child: Image.file(
                                        File(_watermarkedImagePath!),
                                        fit: BoxFit.contain,
                                        errorBuilder:
                                            (context, error, stackTrace) {
                                          return const Center(
                                            child: Column(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: [
                                                Icon(Icons.error,
                                                    color: Colors.red),
                                                Text('图片加载失败',
                                                    style: TextStyle(
                                                        color: Colors.red,
                                                        fontSize: 12)),
                                              ],
                                            ),
                                          );
                                        },
                                      ),
                                    )
                                  : const Center(
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Icon(Icons.image_not_supported,
                                              color: Colors.grey),
                                          Text('图片不存在',
                                              style: TextStyle(
                                                  color: Colors.grey,
                                                  fontSize: 12)),
                                        ],
                                      ),
                                    ),
                            ),
                          ),
                          if (_imageInfo != null) ...[
                            const SizedBox(height: 8),
                            Text(
                              "图片信息: ${_imageInfo!['width']}×${_imageInfo!['height']} | ${_imageInfo!['fileSizeFormatted']}",
                              style: const TextStyle(
                                  fontSize: 12, color: Colors.grey),
                            ),
                          ],
                        ],
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
